CREATE FUNCTION fnPeriodFirstDay
-- First day date for some date
(
  @DatePeriod DATETIME
)
RETURNS DATETIME
AS  
BEGIN 
  RETURN DATEADD(DAY, -DAY(@DatePeriod) + 1, @DatePeriod)
END
GO
CREATE FUNCTION fnPeriodLastDay
-- Last day date for some date
(
  @DatePeriod DATETIME
)
RETURNS DATETIME
AS  
BEGIN 
  RETURN DATEADD(DAY, -1, DATEADD(MONTH, 1, dbo.fnPeriodFirstDay(@DatePeriod)))
END
GO
ALTER PROCEDURE [dbo].[spAPI_Promotion_Add]
(
	@Token VARCHAR(255)
)
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @IdResult INT
	DECLARE @Result VARCHAR(100)
	
	DECLARE @BusinessId INT
	DECLARE @PromotionId INT
	DECLARE @BaseCost MONEY
	
	SET @IdResult = 0
	EXEC spAPI_Business_CheckToken @Token = @Token, @Result = @IdResult OUT, @BusinessId = @BusinessId OUT
	
	IF (@Result = 1)
	BEGIN
		IF EXISTS(SELECT 1 
				FROM Business
				WHERE (BusinessId = @BusinessId)
					AND (ISNULL(CreditCardName, '') = '')
					AND (ISNULL(CreditCardNo, '') = '')
					AND (ISNULL(CreditCardPin, '') = ''))
			SET @Result = -1
		ELSE IF EXISTS(SELECT 1 
				FROM Business
				WHERE (BusinessId = @BusinessId)
					AND (dbo.fnPeriodLastDay(CreditCardExpDate) < GETDATE()))
			SET @Result = -2
	END			
	
	IF @IdResult = 1
	BEGIN
		INSERT INTO Promotion
		(BusinessId)
		VALUES (@BusinessId)
		
		SET @PromotionId = SCOPE_IDENTITY()
		
		SELECT @BaseCost = FixedCost
		FROM BaseCostTiming
		WHERE BaseCostTimingId = 1
		
		SET @Result = CONVERT(VARCHAR(20), @PromotionId) + ';' + CONVERT(VARCHAR(50), @BaseCost)
	END
		
	SELECT @IdResult AS IdResult, ISNULL(@Result, '') AS Result 
END
GO
CREATE PROCEDURE spAPI_Promotion_GetPayInfo
(
	@Token VARCHAR(255),
	@PromotionId INT
)
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @IdResult INT
	DECLARE @BusinessId INT
	
	SET @IdResult = 0
	EXEC spAPI_Business_CheckToken @Token = @Token, @Result = @IdResult OUT, @BusinessId = @BusinessId OUT
	
	IF (@IdResult = 1)
		IF (NOT EXISTS(SELECT 1 FROM Promotion (NOLOCK) WHERE BusinessId = @BusinessId AND PromotionId = @PromotionId))
			SET @IdResult = -1

	IF @IdResult = 1
		SELECT @IdResult AS IdResult, 
			Promotion.CampaignBudget,
			Business.CreditCardExpDate, Business.CreditCardName, Business.CreditCardNo, Business.CreditCardPin
		FROM Promotion (NOLOCK) INNER JOIN Business (NOLOCK) ON Promotion.BusinessId = Business.BusinessId
		WHERE Promotion.PromotionId = @PromotionId
	ELSE
		SELECT @IdResult AS IdResult
END
GO